﻿using System;
using System.Linq;
using System.Web.UI.WebControls;

namespace ECommerce.Controls
{
	public partial class NewProducts_Left : BaseUserControl
	{
		private Service.IProductService _ProductService;

		protected void Page_PreRender(object sender, EventArgs e)
		{
			BindData();
		}

		protected void RepeaterNewProducts_ItemDataBound(object sender, RepeaterItemEventArgs e)
		{
			if (e.Item.DataItem != null)
			{
				System.Web.UI.WebControls.HyperLink hlImg = (System.Web.UI.WebControls.HyperLink)e.Item.FindControl("HyperLinkProdPic");

				hlImg.NavigateUrl = "~/ProductDetail.aspx?productid=" + ((Data.Entity.Product)e.Item.DataItem).ProductID;
				hlImg.ImageUrl = "~/PictureHandler.ashx?picturesize=170&productid=" + ((Data.Entity.Product)e.Item.DataItem).ProductID;
			}
		}

		private void BindData()
		{
			if (SiteContext.Current == null)
			{
				Server.Transfer("~/HomePage.aspx");
			}

			if (SiteContext.Current.WorkingLanguage != null)
			{
				if (_ProductService == null)
				{
					_ProductService = new Service.ProductService();
				}

				var productByLang = _ProductService.GetProductsByLanguage(SiteContext.Current.WorkingLanguage.LanguageId);

				if (productByLang != null)
				{
					var products = (from p in productByLang
									orderby p.ShowOnHomePage
									select p).Skip(6).Take(6);

					RepeaterNewProducts.DataSource = products;
					RepeaterNewProducts.DataBind();
				}
			}
		}
	}
}